import os
from datetime import timedelta
from dotenv import load_dotenv

class Config:
    @classmethod
    def init_app(cls, app):
        # 加载.env文件
        load_dotenv()
        
        # 数据库配置
        app.config['SQLALCHEMY_DATABASE_URI'] = cls.get_db_uri()
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
        # 连接池配置
        app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
            'pool_size': 20,
            'max_overflow': 10,
            'pool_timeout': 30,
            'pool_recycle': 3600
        }
        
        # JWT配置
        app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY')
        app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=24)  # 24小时有效期
    
    @classmethod
    def get_db_uri(cls):
        return (
            f"mysql+pymysql://{os.getenv('DB_USER')}:{os.getenv('DB_PASSWORD')}"
            f"@{os.getenv('DB_HOST')}:{os.getenv('DB_PORT')}/{os.getenv('DB_NAME')}"
            "?charset=utf8mb4"
        )
